package com.qfedu.scode.service.impl;

import com.qfedu.scode.config.RedisKeyConfig;
import com.qfedu.scode.config.SystemConfig;
import com.qfedu.scode.dto.SmsCodeDto;
import com.qfedu.scode.entity.Smslog;
import com.qfedu.scode.dao.SmslogDao;
import com.qfedu.scode.service.intf.SmslogService;
import com.qfedu.scode.util.AliSmsUtil;
import com.qfedu.scode.util.NumRandomUtil;
import com.qfedu.scode.util.RedissonUtil;
import com.qfedu.scode.util.StringUtil;
import com.qfedu.scode.vo.R;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: StartCoding
 * @description: 一款真正的后端源码生成器，助力轻松入门Java程序
 * @author: Feri(老邢)
 * @create: 2021-01-06 11:09:45
 */
@Service
public class SmslogServiceImpl implements SmslogService{
    /*
    *注入持久层对象*/
    @Autowired
    private SmslogDao dao;
    /*
    * 查询 所有数据*/
    @Override
    public R queryAll() {
        return R.ok(dao.selectAll());
    }

    @Override
    public R sendCode(String phone) {
        //非法参数校验
        if(StringUtil.isNoEmpty(phone)){
            //生成验证码
            int code= NumRandomUtil.createRandomNum(SystemConfig.SMS_CODELEN);
            //发送短信
            if(AliSmsUtil.sendSmsCode(phone,code)){
                //验证码 10分钟有效期
                RedissonUtil.setStr(RedisKeyConfig.SMS_CODE+phone,code,RedisKeyConfig.SMS_CODE_TIMES);
                //记录数据到数据库
                dao.insert(new Smslog(phone,SystemConfig.SMS_CODEADD,phone+"注册新用户，短信验证码"));
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public R checkCode(SmsCodeDto dto) {
        //参数的非法校验
        if(dto!=null) {
            if (StringUtil.isNoEmpty(dto.getPhone()) && dto.getCode() > 0) {
                String key=RedisKeyConfig.SMS_CODE+dto.getPhone();
                //验证Redis key是否存在
                if(RedissonUtil.isHave(key)){
                    //校验是否正确
                    if(dto.getCode()== Integer.parseInt(RedissonUtil.getStr(key))){
                        return R.ok();
                    }
                }
            }
        }
        return R.fail();
    }
}